<template>
  <div id="app">
    <!-- 顶部导航栏 -->
    <div id="topNav">
      <button @click="goBack" class="backButton">
        <img src="/src/assets/images/start-page/fanhui.png" alt="返回">
      </button>
      <div id="navTitle">农智通智能ai</div>
    </div>
    
    <div id="chatBox" ref="chatBox">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
        <p v-html="message.content"></p>
      </div>
      <div v-if="isTyping" class="message ai-message">
        <p><strong>农智通:</strong> <span>...</span></p>
      </div>
    </div>
    
    <div id="inputArea">
      <input type="text" id="userInput" v-model="userInput" @keydown.enter="sendMessage" placeholder="输入消息...">
      <button @click="sendMessage">Send</button>
    </div>
    
    <!-- 引用 BottomNav.vue 组件 -->
    <BottomNav />
  </div>
</template>

<script>
// 引入 BottomNav 组件
import BottomNav from '@/views/BottomNav.vue';

export default {
  components: {
    BottomNav
  },
  data() {
    return {
      messages: [],
      userInput: '',
      isTyping: false
    };
  },
  mounted() {
    this.addWelcomeMessage();
  },
  methods: {
    goBack() {
      // 返回到首页的逻辑
      this.$router.push('/homepage'); // 假设您使用了 vue-router
    },
    addWelcomeMessage() {
      this.messages.push({
        type: 'ai-message',
        content: '<p><strong>农智通:</strong> 我是农智通，一款专为农业领域设计的 AI 知识助手</p>'
      });
      this.scrollToBottom();
    },
    sendMessage() {
      if (!this.userInput) return;

      // 用户消息
      this.messages.push({
        type: 'user-message',
        content: `<p>${this.userInput}</p>`
      });

      // 清空输入框
      const userInput = this.userInput;
      this.userInput = '';

      // 设置正在输入标志
      this.isTyping = true;

      // AI 消息
      const newAIMessage = {
        type: 'ai-message',
        content: '<p><strong>农智通:</strong><span></span></p>'
      };
      this.messages.push(newAIMessage);

      this.$nextTick(() => {
        const textSpan = this.$refs.chatBox.children[this.messages.length - 1].querySelector('span');
        this.scrollToBottom();

        const options = {
          method: 'POST',
          headers: {
            Authorization: 'Bearer sk-aommhsnabnoqfytqmwcwbgipdvgrgyovhqvjpnxjwyigcpih', // 注意：不要在客户端硬编码敏感信息
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: "Qwen/QwQ-32B",
            messages: [{ role: "user", content: userInput }],
            stream: true,
            max_tokens: 256,
            temperature: 0.5,
            top_p: 0.8
          })
        };

        fetch('https://api.siliconflow.cn/v1/chat/completions', options)
          .then(async (response) => {
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let resultText = '';
            while (true) {
              const { done, value } = await reader.read();
              if (done) break;
              const chunk = decoder.decode(value, { stream: true });
              const lines = chunk.split('\n');
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  const dataStr = line.slice(6).trim();
                  if (dataStr === '[DONE]') {
                    this.isTyping = false; // 结束正在输入标志
                    break;
                  }
                  try {
                    const data = JSON.parse(dataStr);
                    const token = data.choices?.[0]?.delta?.content || '';
                    resultText += token;
                    textSpan.textContent = resultText;
                    this.scrollToBottom();
                  } catch (e) {
                    console.error('JSON 解析失败:', e);
                  }
                }
              }
            }
          })
          .catch(err => {
            console.error('请求失败:', err);
            textSpan.textContent += '（连接中断或服务不可用）';
            this.isTyping = false; // 结束正在输入标志
          });
      });
    },
    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
/* 全局基础样式 */
* {
  box-sizing: border-box;
}

#app {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 400px;
  height: 100vh;
  border: 1px solid #ccc;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
  overflow: hidden;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

/* 顶部导航栏样式 */
#topNav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #4caf50; /* 更改导航栏颜色 */
  color: #ffffff;
}

.backButton {
  background: none;
  border: none;
  padding: 0;
  margin-left: 10px;
  cursor: pointer;
}

.backButton img {
  width: 24px;
  height: 24px;
}

#navTitle {
  font-size: 18px;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

/* 调整问答框高度 */
#chatBox {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 60px; /* 为底部导航栏腾出空间 */
}

#chatBox p {
  margin: 0;
  padding: 10px 14px;
  border-radius: 15px;
  max-width: 80%;
  word-wrap: break-word;
  line-height: 1.4;
}

.user-message p {
  background-color: #007bff;
  color: white;
  align-self: flex-end;
  border-radius: 15px 5px 5px 15px;
}

.ai-message p {
  background-color: #e5e5ea;
  color: black;
  align-self: flex-start;
  border-radius: 5px 15px 15px 5px;
}

#inputArea {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f4f4f4;
  border-top: 1px solid #ccc;
  position: fixed;
  bottom: 60px; /* 与底部导航栏保持一致 */
  width: 100%;
  max-width: 400px;
  box-sizing: border-box;
}

#userInput {
  flex: 1;
  padding: 6px 14px; /* 减少高度和宽度的内边距 */
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 20px; /* 减少边框半径 */
  outline: none;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: calc(100% - 100px); /* 减少输入框的宽度 */
}

#userInput::placeholder {
  color: #999;
}

button {
  padding: 8px 15px; /* 减少高度和宽度的内边距 */
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 20px; /* 减少边框半径 */
  background-color: #007bff;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

button:hover {
  background-color: #0056b3;
}

.message {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message p {
  margin: 0;
  padding: 10px 14px;
  border-radius: 15px;
  max-width: 80%;
  word-wrap: break-word;
  line-height: 1.4;
  font-size: 14px;
}

.user-message p {
  background-color: #007bff;
  color: white;
  align-self: flex-end;
  border-radius: 15px 5px 5px 15px;
}

.ai-message p {
  background-color: #e5e5ea;
  color: black;
  align-self: flex-start;
  border-radius: 5px 15px 15px 5px;
}

/* 加载动画样式 */
#chatBox .message.ai-message p span {
  display: inline-block;
  width: 30px;
  height: 1em;
  background: url('/src/assets/images/loading.gif') no-repeat center center;
  background-size: cover;
}
</style>
